package News.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import News.entity.Topic;
import News.util.DBUtil;

public class CategoryDao {
	public List<Topic> finAll() {
		String sql = "select *from Topic";
		List<Topic> dates = new ArrayList<Topic>();
		Connection conn = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				Topic s = new Topic();
				s.setTid(rs.getInt("tid"));
				s.setTname(rs.getString("tname"));
				dates.add(s);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(rs, ps, conn);
		}
		return dates;
	}

	public int delete(long id) {
		String sql = "DELETE FROM Topic WHERE tid=?";
		return DBUtil.executeUpdate(sql, id);
	}

	public int add(Topic s) {
		String sql = "insert INTO Topic (tname) VALUES(?)";
		return DBUtil.executeUpdate(sql, s.getTname());
	}

	public int update(Topic s) {
		String sql = "update Topic set tname=?where tid=?";
		return DBUtil.executeUpdate(sql, s.getTname(), s.getTid());

	}

	public List<Topic> findTop() {
		String sql = "select * from Topic ORDER  by tid LIMIT 1";
		List<Topic> dates1 = new ArrayList<Topic>();
		Connection conn = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				Topic s = new Topic();
				s.setTid(rs.getInt("tid"));
				s.setTname(rs.getString("tname"));
				dates1.add(s);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(rs, ps, conn);
		}
		return dates1;
	}
}
